﻿
using System;
using System.Security.Cryptography;
using System.Text;

namespace UFrame
{
    /// <summary>
    /// 常用的加密和签名方法
    /// </summary>
    public class SignTool
    {
        public static string Base64Encode(string content)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(content);
            return Convert.ToBase64String(bytes);
        }

        public static string Base64Decode(string content)
        {
            byte[] bytes = Convert.FromBase64String(content);
            return Encoding.UTF8.GetString(bytes);
        }

        public static string HMACSHA256ToBase64(string message, string secret)
        {
            secret = secret ?? "";
            var encoding = new System.Text.ASCIIEncoding();
            byte[] keyByte = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(message);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                return Convert.ToBase64String(hashmessage);
            }
        }

        public static string HMACSHA256(string message, string secret)
        {
            secret = secret ?? "";
            var encoding = new System.Text.UTF8Encoding();
            byte[] keyByte = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(message);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < hashmessage.Length; i++)
                {
                    builder.Append(hashmessage[i].ToString("x2"));
                }

                return builder.ToString();
            }
        }
        
        
        /// <summary>
        /// 生产Aes字符串
        /// </summary>
        /// <returns></returns>
        public static string CreateAes()
        {
            byte[] aes = new byte[33];
            for (int i = 0; i < 32; ++i)
            {
                int v = UnityEngine.Random.Range(65, 123);//asc
                aes[i] = (byte)v;
            }
            aes[32] = (byte)0;
            string aesStr = Encoding.UTF8.GetString(aes);
            return aesStr;
        }
        
        
        
        
    }
}